let iMap = new Map({
  id: 'mapid',
  center: CENTER,
  zoom: 13,
  tileLayerUrl: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
  click: onMapClick
})

iMap.getMap().on('zoomend', function (e) {
  updatePoint();
})

function onMapClick(e) {
  console.log(e.latlng)
}

var points = [];
let sound = audioPlay()
var active = {
  美愿: true,
  小故事: true,
  任务单: true,
  导游内容: true
}

//坐标点切换
$('.nav-title').click(function (e) {
  // var $dom = $(e.target);
  // var flag = $dom.toggleClass('active').hasClass('active')
  // var st = $.trim($dom.text());
  // console.log(st, flag)
  $('.nav-tab .nav-title').removeClass('active');

  for (const key in active) {
    if (key.indexOf('美') > -1) {
      active[key] = false;
    }
  }

  var st = $.trim($(e.target).text());

  $(e.target).addClass('active');
  active[st] = true;
  updatePoint()
})

//跳转设置
$('.tool').click(function () {
  wxutil.navigateTo({
    url: '../user/user'
  })
});

window.API.getPointList(function (arr) {
  // console.log(arr)
  initPoint(arr)
})

function updatePoint() {
  let zoom = iMap.getZoom();
  console.log(zoom)
  points.forEach(point => {
    let item = point._data;
    if (active[item.type]) {
      if (isInZoom(item, zoom)) {
        iMap.addOverlay(point)
      } else {
        iMap.removeOverlay(point)
      }
    } else {
      iMap.removeOverlay(point)
    }
  });
}

function initPoint(list) {
  list.forEach(item => {
    item.click = markerClickHandle;
    let marker = iMap.createPoint(item);
    points.push(marker)
  });
  updatePoint();
}

function markerClickHandle(e) {
  // console.log(e)
  let marker = e.target;
  let data = marker._data;
  switch (data.type) {
    case TYPE.XIAO_GU_SHI: // 小故事
    case TYPE.REN_WU_DAN: // 任务单
      // let strJson = JSON.stringify(data)
      wxutil.navigateTo({
        url: '../story/story?id=' + data.id
      })
      break;
    case TYPE.MEI_YUAN: // 美愿
    case TYPE.MEI_LI:
    case TYPE.MEI_WU:
    case TYPE.MEI_SU:
      wxutil.navigateTo({
        url: '../beautifulGoods/good?id=' + data.id
      })
      break;
    case TYPE.DAO_YOU: // 导游
      // console.log(data)
      sound.setSrc(data.soundUrl);
      sound.replay()
      break;
    default:
      break;
  }
}

function isInZoom(item, zoom) {
  if (item.minZoom) {
    if (item.minZoom > zoom) return false;
  }
  if (item.maxZoom) {
    if (item.maxZoom < zoom) return false;
  }
  return true;
}